/**
* @version v 1.1.0 2009/10/19
* @package Nerv Widgets, nw.js
* @subpackage Nerv Calendar, calendar.js
* @author Manuele Castellan <manuele.castellan@gmail.com>
*
* @copyright    Copyright (C) Copyright (c) 2009 Manuele Castellan. All rights reserved.
* @license        GNU/GPLv3, see LICENSE
*
*  This program is free software: you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation, either version 3 of the License, or
*  (at your option) any later version.
*
*  This program is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  You should have received a copy of the GNU General Public License
*  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*
*/

NW3.calendar = {
	Date : function(params){
		var oInputText = new NW3.form.Text(params.name);
		
		var oContainer = document.createElement('span');
		
		var obj = {
			name : params.name,
			input : oInputText,
			input_width : 105,
			object : oContainer,
			status : ((params.status) ? params.status : 'enabled'),
			value : params.value,
			
			onkeyup : (params.onkeyup) ? params.onkeyup : null
		}
		
		obj.ocal = new NW3.calendar.Calendar({
			input : obj.input,
			format : params.format,
			button : params.button,
			onkeyup : obj.onkeyup
		});
		
		obj.setWidth = function(val){
			if(val){
				obj.input_width = val;
			}
			obj.input.setWidth(obj.input_width);
		}
		
		obj.setValue = function(val){
			if(val) obj.input.setValue(val);
		}
		
		obj.getStatus = function(){
			return obj.status;
		}
		
		obj.setStatus = function(op){
			obj.input.setStatus(op);
			obj.ocal.setStatus(op);
			
			obj.status = op;
		}
		
		obj.print = function(){
			obj.setWidth();
			obj.input.setStatus(obj.getStatus());
			
			obj.input.onMouseDown(function(){
				obj.ocal.show();
				if(obj.onkeyup) obj.onkeyup();
			});
			
			obj.setValue(obj.value);
			obj.setStatus(obj.status);
			
			obj.input.print();
			
			obj.ocal.print();
		}
		
		obj.replace = function(targetElement){
			NW3.core.object.replace(targetElement, obj.output());
		};
		
		obj.insertAfter = function(targetElement){
			NW3.core.object.insertAfter(obj.output(), targetElement);
		};
		
		obj.insertBefore = function(targetElement){
			NW3.core.object.insertBefore(obj.output(), targetElement);
		};
		
		obj.appendChild = function(targetElement){
			NW3.core.object.appendChild(obj.output(), targetElement);
		};
		
		return obj;
	},
	
	Calendar : function(params) {
		var oWin_ = new NW3.Window;
		oWin_.setWidth('205');
		oWin_.setHeight('272');
		oWin_.setTitle(NW3.lang.Calendar);
		oWin_.setButtonClose();
		//oWin_.setButtonHelp();
		//oWin_.setIcon('img/email.png');
		oWin_.setDraggable(true);
		oWin_.setDragEffect({
			effect : 'opacity',
			value  : 80
		});
		oWin_.hide();
		
		var week_days = [
			NW3.lang.Sunday,
			NW3.lang.Monday,
			NW3.lang.Tuesday,
			NW3.lang.Wednesday,
			NW3.lang.Thursday,
			NW3.lang.Friday,
			NW3.lang.Saturday
		];
		
		var arr_months = [
			NW3.lang.January,
			NW3.lang.February,
			NW3.lang.March,
			NW3.lang.April,
			NW3.lang.May,
			NW3.lang.June,
			NW3.lang.July,
			NW3.lang.August,
			NW3.lang.September,
			NW3.lang.October,
			NW3.lang.November,
			NW3.lang.December
		];
		
		var oContainer = document.createElement('span');
		var oCalContainer = document.createElement('span');
		
		
		var obj = {
			object : oContainer,
			calobject : oCalContainer,
			win		: oWin_,
			otarget : params.input,				// oggetto input text
			format : params.format,				// formato data
			button : (params.button == true) ? true : false,
			value : params.value,
			width: '199px',					// width 
			status : 'enabled',
			
			onkeyup : (params.onkeyup) ? params.onkeyup : null,
			
			classprefix : 'NWCalendar',
			week_days : week_days,			// array nomi giorni settimana
			arr_months : arr_months			// array nomi mesi
		}
		
		obj.getStatus = function(){
			return obj.status;
		}
		
		obj.setStatus = function(op){
			if(op) obj.status = op;
		}
		
		/* nasconde calendario */
		obj.hide = function(){
			obj.win.hide();
		}
	
		/* vasualizza calendario */
		obj.show = function(){
			winTop = NW3.core.object.getPosTop(obj.otarget);
			winLeft = NW3.core.object.getPosLeft(obj.otarget);
			
			otargetWidth = obj.otarget.offsetWidth;
			if(!otargetWidth){
				otargetWidth = obj.otarget.getWidth();
				
				winTop = NW3.core.object.getPosTop(obj.otarget.output());
				winLeft = NW3.core.object.getPosLeft(obj.otarget.output());
			}
			
			
			obj.win.setTop(winTop);
			obj.win.setLeft(parseInt(winLeft) + parseInt(otargetWidth));
			
			obj.win.show();
		}
		
		/** recupera valore da input text */
		obj.getValue = function(){
			switch (typeof(obj.otarget)) {
				case 'object':
					if(obj.otarget.nodeType == 1){
						val = obj.otarget.value;
					}
					else{
						val = obj.otarget.getValue();
					}
					break;
				default:
					break;
			}
			//alert(obj.otarget.getValue());
			return NW3.core.string.parseDate(val, obj.format);
		}
		
		/** setta valore nel input text */
		obj.setValue = function(val){
			if(val){
				obj.value = val;
			}
			
			switch (typeof(obj.otarget)) {
				case 'object':
					if(obj.otarget.nodeType == 1){
						obj.otarget.value = NW3.core.string.parseDate(obj.value, obj.format);
					}
					else{
						obj.otarget.setValue(
							NW3.core.date.dateFormat(
								NW3.core.string.stringToDate(obj.value)
							, obj.format)
						);
					}
					break;
				default:
					break;
			}
		}
		
		obj.setWidth = function(val){
			if(val){
				obj.width = val;
			}
			obj.calobject.style.width = obj.width;
		}
		
		/* crea calendario */
		obj.createCalendar = function(dt_datetime){
			NW3.core.object.removeChildsNodes(obj.calobject);
			
			var options = {
				onlyThisMonth : true,			//	stampa solo giorni del mese
				n_weekstart	:	1				//	inizio settimana (0 sunday , 1 monday)
			}
			
			var oCalMenu = new NW3.calendar.createCalendarMenu(dt_datetime, obj, options);
			obj.calobject.appendChild(oCalMenu);
			
			var oCalDays = new NW3.calendar.createCalendarDays(dt_datetime, obj, options);
			obj.calobject.appendChild(oCalDays);
			
			var oCalTime = new NW3.calendar.createCalendarTime(dt_datetime, obj, options);
			obj.calobject.appendChild(oCalTime);
			
			obj.calobject.className = 'NWCalendar';
		}
		
		obj.output = function(){
			obj.setWidth();
			obj.calobject.style.display = 'block';
			
			switch (typeof(obj.otarget)) {
				case 'object':
					if(obj.otarget.nodeType == 1){
						dt_datetime = obj.otarget.value;
					}
					else{
						dt_datetime = obj.otarget.getValue();
					}
					break;
				default:
					break;
			}
			
			var dt_datetime = NW3.core.string.stringToDate(obj.getValue());
			obj.createCalendar(dt_datetime);
			
			
			
			
			obj.win.add(obj.calobject);
			
			obj.object.appendChild(obj.win.output());
			
			/* creo bottone */
			if(obj.button){
				oCalButton = new NW3.form.Button();
				oCalButton.setText('...');
				oCalButton.setWidth('20px');
				oCalButton.onMouseUp(function(){
					obj.show();
					if(obj.onkeyup) obj.onkeyup();
				});
				
				oCalButton.setStatus(obj.getStatus());
				
				//oCalButton.print();
				
				obj.object.appendChild(oCalButton.output());
			}
			
			return obj.object;
		}
		
		obj.print = function(){
			NW3.core.object.print(obj.output());
		}
		
		obj.replace = function(targetElement){
			NW3.core.object.replace(targetElement, obj.output());
		};
		
		obj.insertAfter = function(targetElement){
			NW3.core.object.insertAfter(obj.output(), targetElement);
		};
		
		obj.insertBefore = function(targetElement){
			NW3.core.object.insertBefore(obj.output(), targetElement);
		};
		
		obj.appendChild = function(targetElement){
			NW3.core.object.appendChild(obj.output(), targetElement);
		};
		
		return obj;
	},
	
	/* crea menu */
	createCalendarMenu : function(dt_datetime, obj, options){
		var n_weekstart = options.n_weekstart; // giorno di inizio settimana (0 = 'Sunday' or 1 = 'Monday')
		
		/*var dt_firstday = new Date(dt_datetime);
		dt_firstday.setDate(1);
		dt_firstday.setDate(1-(7+dt_firstday.getDay()-n_weekstart)%7);
		var dt_lastday = new Date(dt_next_month);
		dt_lastday.setDate(0);*/
		
		
		var oToolbar = new NW3.toolbar.Toolbar();
		
		// button left
		var oButtonLeft = new NW3.toolbar.Button();
		//oButtonLeft.setImage(NW3.core.getScriptUrl() + 'styles/' + NW3.core.getThemeUrl('calendar') + '/calButtonLeft.png');
		/*oButtonLeft.setText('File');
		oButtonLeft.setTitle('Click for email options');*/
		oButtonLeft.setClass('NWCalendarButtonLeft');
		oButtonLeft.onClick(function(id){
			var dt_prev_month = NW3.core.string.stringToDate(obj.getValue());
			dt_prev_month.setMonth(dt_datetime.getMonth()-1);
			obj.setValue(NW3.core.date.dateFormat(dt_prev_month));
			obj.createCalendar(dt_prev_month);
		});
		
		oToolbar.addButton(oButtonLeft);
		
		
		// label
		var oTLabel = new NW3.toolbar.Label();
		oTLabel.setClass(obj.classprefix + 'MenuTitle');
		var title = obj.arr_months[dt_datetime.getMonth()] + ' ' + dt_datetime.getFullYear();
		oTLabel.setText(title);
		oToolbar.addButton(oTLabel);
		
		
		// button right
		var oButtonRight = new NW3.toolbar.Button();
		//oButtonRight.setImage(NW3.core.getScriptUrl() + 'theme/' + NW3.core.getThemeUrl('calendar') + '/calButtonRight.png');
		/*oButtonRight.setText('File');
		oButtonRight.setTitle('Click for email options');*/
		oButtonRight.setClass('NWCalendarButtonRight');
		oButtonRight.onClick(function(id){
			var dt_next_month = NW3.core.string.stringToDate(obj.getValue());
			dt_next_month.setMonth(dt_datetime.getMonth()+1);
			obj.setValue(NW3.core.date.dateFormat(dt_next_month));
			obj.createCalendar(dt_next_month);
		});
		
		oToolbar.addButton(oButtonRight);
		
		return oToolbar.output();
	},
	
	/** crea tabella delle ore */
	createCalendarTime : function(dt_datetime, obj, options){
		// formatta ore
		getHourValue = function(n){
			h = new Date();
			h.setHours(n);
			
			return NW3.core.date.dateFormat(h, 'H');
		}
		// formatta minuti
		getMinValue = function(n, op){
			m = new Date();
			m.setMinutes(n);
			
			return NW3.core.date.dateFormat(m, 'i');
		}
		
		
		// creo tabella
		var oTable = new NW3.table.Table;
		oTable.setClass('NWCalendarTableHours');
		oTable.setAlign('center');
		oTable.setBorder(0);
		oTable.setCellPadding(3);
		oTable.setCellSpacing(1);
		
		// time
		var oTableTr = new NW3.table.Tr;
		var oTableTd = new NW3.table.Td;
		oTableTr.add(oTableTd);
		oTable.add(oTableTr);
		
		var oTableTime = new NW3.table.Table;
		oTableTime.setClass('NWCalendarTableHours');
		oTableTd.add(oTableTime.output());
		var oTableTimeTr = new NW3.table.Tr;
		oTableTime.add(oTableTimeTr);
		
		var oTitle = document.createTextNode(NW3.lang.Hour);
		var oTableTimeTd = new NW3.table.Td;
		oTableTimeTd.setClass('NWCalendarTableHoursTitle');
		oTableTimeTd.add(oTitle);
		oTableTimeTr.add(oTableTimeTd);
		
		
		/* HOURS */
		var oTableTimeTd2 = new NW3.table.Td;
		
		var oDimmerUp = new NW3.form.dimmer.Dimmer('hour');
		oDimmerUp.setWidth('14');
		oDimmerUp.setValue(getHourValue(NW3.core.string.stringToDate(obj.getValue()).getHours()));
		
		oButtonUpUp = new NW3.form.dimmer.Button();
		oButtonUpUp.onMouseUp(function(){
			var hHourUp = getHourValue(new Number(oDimmerUp.getValue()) + 1);
			oDimmerUp.setValue(hHourUp);
			var hUpdate = NW3.core.string.stringToDate(obj.getValue());
			hUpdate.setHours(hHourUp);
			obj.setValue(NW3.core.date.dateFormat(hUpdate));
		});
		
		oButtonUpDown = new NW3.form.dimmer.Button();
		oButtonUpDown.onMouseUp(function(){
			var hHourDown = getHourValue(new Number(oDimmerUp.getValue()) - 1);
			oDimmerUp.setValue(hHourDown);
			var hUpdate = NW3.core.string.stringToDate(obj.getValue());
			hUpdate.setHours(hHourDown);
			obj.setValue(NW3.core.date.dateFormat(hUpdate));
		});
		
		oDimmerUp.addButtons(oButtonUpUp, oButtonUpDown);
		
		oTableTimeTd2.add(oDimmerUp.output());
		oTableTimeTr.add(oTableTimeTd2);
		
		
		/* MINUTES */
		var oTableTimeTd3 = new NW3.table.Td;
		
		var oDimmerDown = new NW3.form.dimmer.Dimmer('minute');
		oDimmerDown.setWidth('14');
		oDimmerDown.setValue(getMinValue(NW3.core.string.stringToDate(obj.getValue()).getMinutes()));
		
		oDimmerDownUp = new NW3.form.dimmer.Button();
		oDimmerDownUp.onMouseUp(function(){
			var mMinUp = getMinValue(new Number(oDimmerDown.getValue()) + 1);
			oDimmerDown.setValue(mMinUp);
			var mUpdate = NW3.core.string.stringToDate(obj.getValue());
			mUpdate.setMinutes(mMinUp);
			obj.setValue(NW3.core.date.dateFormat(mUpdate));
		});
		
		oButtonDownDown = new NW3.form.dimmer.Button();
		oButtonDownDown.onMouseUp(function(){
			var mMinDown = getMinValue(new Number(oDimmerDown.getValue()) - 1);
			oDimmerDown.setValue(mMinDown);
			var mUpdate = NW3.core.string.stringToDate(obj.getValue());
			mUpdate.setMinutes(mMinDown);
			obj.setValue(NW3.core.date.dateFormat(mUpdate));
		});
		
		oDimmerDown.addButtons(oDimmerDownUp, oButtonDownDown);
		
		oTableTimeTd3.add(oDimmerDown.output());
		oTableTimeTr.add(oTableTimeTd3);
		
		/*var oHour = new NW3.form.Text('hour')
		oHour.setWidth('14');
		oHour.setValue(getHourValue(NW3.core.string.stringToDate(obj.getValue()).getHours()));
		var oTableTimeTd1 = new NW3.table.Td;
		oTableTimeTd1.add(oHour.output());
		oTableTimeTr.add(oTableTimeTd1);
		
		var oTableTimeTd2 = new NW3.table.Td;
		oTableTimeTd2.setClass('NWCalendarTableHoursDimmerLeft');
		// dimmer
		var oButtonUp1 = new NW3.form.Button();
		oButtonUp1.setClass('tFormDimmerUp');
		oButtonUp1.onMouseUp(function(){
			var hHourUp = getHourValue(new Number(oHour.getValue()) + 1);
			oHour.setValue(hHourUp);
			var hUpdate = NW3.core.string.stringToDate(obj.getValue());
			hUpdate.setHours(hHourUp);
			obj.setValue(NW3.core.date.dateFormat(hUpdate));
		});
		oTableTimeTd2.add(oButtonUp1.output());
		// --
		var oButtonDown1 = new NW3.form.Button();
		oButtonDown1.setClass('tFormDimmerDown');
		oButtonDown1.onMouseUp(function(){
			var hHourDown = getHourValue(new Number(oHour.getValue()) - 1);
			oHour.setValue(hHourDown);
			var hUpdate = NW3.core.string.stringToDate(obj.getValue());
			hUpdate.setHours(hHourDown);
			obj.setValue(NW3.core.date.dateFormat(hUpdate));
		});
		oTableTimeTd2.add(oButtonDown1.output());
		// dimmer
		oTableTimeTr.add(oTableTimeTd2);*/
		
		
		/*var oMin = new NW3.form.Text('min')
		oMin.setWidth('14');
		oMin.setValue(getMinValue(NW3.core.string.stringToDate(obj.getValue()).getMinutes()));
		var oTableTimeTd3 = new NW3.table.Td;
		oTableTimeTd3.add(oMin.output());
		oTableTimeTr.add(oTableTimeTd3);
		
		var oTableTimeTd4 = new NW3.table.Td;
		oTableTimeTd4.setClass('NWCalendarTableHoursDimmerRight');
		// dimmer
		var oButtonUp2 = new NW3.form.Button();
		oButtonUp2.setClass('tFormDimmerUp');
		oButtonUp2.onMouseUp(function(){
			var mMinUp = getMinValue(new Number(oMin.getValue()) + 1);
			oMin.setValue(mMinUp);
			var mUpdate = NW3.core.string.stringToDate(obj.getValue());
			mUpdate.setMinutes(mMinUp);
			obj.setValue(NW3.core.date.dateFormat(mUpdate));
		});
		oTableTimeTd4.add(oButtonUp2.output());
		// --
		var oButtonDown2 = new NW3.form.Button();
		oButtonDown2.setClass('tFormDimmerDown');
		oButtonDown2.onMouseUp(function(){
			var mMinDown = getMinValue(new Number(oMin.getValue()) - 1);
			oMin.setValue(mMinDown);
			var mUpdate = NW3.core.string.stringToDate(obj.getValue());
			mUpdate.setMinutes(mMinDown);
			obj.setValue(NW3.core.date.dateFormat(mUpdate));
		});
		oTableTimeTd4.add(oButtonDown2.output());
		// dimmer
		oTableTimeTr.add(oTableTimeTd4);*/
		
		
		return oTable.output();
	},
	
	/* crea tabella dei giorni */
	createCalendarDays : function(dt_datetime, obj, options){
		var n_weekstart = options.n_weekstart; // giorno di inizio settimana (0 = 'Sunday' or 1 = 'Monday')
		
		var dt_firstday = new Date(dt_datetime);
		dt_firstday.setDate(1);
		dt_firstday.setDate(1-(7+dt_firstday.getDay()-n_weekstart)%7);
		
		var dt_current_day = new Date(dt_firstday);
		
		// creo tabella
		var oTable = new NW3.table.Table;
		oTable.setClass('NWCalendarTableDays');
		oTable.setBorder(0);
		oTable.setCellPadding(4);
		oTable.setCellSpacing(0);
		//oTable.className = 'NwCalendar';
		
		
		// stampo titolo giorni
		var oTableTr = new NW3.table.Tr;
		var oTableTh = new Array();
		for (var n=0; n<7; n++){
			oTableTh[n] = new NW3.table.Th;
			oTableTh[n].setClass('NWCalendarTableDaysTh');
			var title = document.createTextNode(obj.week_days[(n_weekstart+n)%7].substr(0,3));
			oTableTh[n].add(title);
			oTableTr.add(oTableTh[n]);
		}
		oTable.add(oTableTr);
		
		
		tr = 0;
		d = 0;
		var oLinks = new Array();
		while (dt_current_day.getMonth() == dt_datetime.getMonth() || dt_current_day.getMonth() == dt_firstday.getMonth()) {
			// stampo intestazioni tabella
			var oTableTr = new NW3.table.Tr;
			for (var n_current_wday=0; n_current_wday<7; n_current_wday++) {
					var oTableTd = new NW3.table.Td;
					oTableTd.setAlign('center');
					oTableTd.setClass('NWCalendarTableDaysTd');
					
					// stampo giorni correnti
					oLinks[d] = document.createElement('a');
					oLinks[d].href = 'javascript:void(0);';
					
					oLinks[d].innerHTML = dt_current_day.getDate();
					oLinks[d].title = NW3.core.date.dateFormat(dt_current_day);
					oLinks[d].onclick = function(){
						var hUpdate = NW3.core.string.stringToDate(obj.getValue());
						title_ = NW3.core.string.stringToDate(this.title);
						title_.setMinutes(hUpdate.getMinutes());
						title_.setHours(hUpdate.getHours());
						title_.setSeconds(hUpdate.getSeconds());
						title = NW3.core.date.dateFormat(title_);
						obj.setValue(title);
						obj.createCalendar(NW3.core.string.stringToDate(title));
					}
					
					if (dt_current_day.getDate() == dt_datetime.getDate() && dt_current_day.getMonth() == dt_datetime.getMonth()){
						// stampo data corrente
						//oTableTd.className = 'cldTableNow';
						//oTableTd.style.background = 'red';
						oTableTd.setClass('NWCalendarTableDaysTdChecked');
						
					} else if (dt_current_day.getDay() == 0 || dt_current_day.getDay() == 6){
						// stampo weekend
						//oTableTd.className = 'cldTableWe';
						//oTableTd.style.background = '#c0c0c0';
						oTableTd.setClass('NWCalendarTableDaysTdWeekend');
					} else {
						// stampo giorni lavorativi
						//oTableTd.className = 'cldTableWork';
						//oTableTd.style.background = '#fff';
						oTableTd.setClass('NWCalendarTableDaysTdWorkdays');
					}
					
					if ( dt_current_day.getMonth() == dt_datetime.getMonth() ){
						// stampo giorni del mese
						oTableTd.add(oLinks[d]);
					} else {
						// stampo giorni di altri mesi
						if(!options.onlyThisMonth) oTableTd.add(oLinks[d]);
					}
					
					
					oTableTr.add(oTableTd);
					dt_current_day.setDate(dt_current_day.getDate()+1);
					
					d++;
			}
			tr++;
			oTable.add(oTableTr);
		}
		
		if(tr < 6){
			var oTableTr = new NW3.table.Tr;
			var oTableTd = new NW3.table.Td;
			oTableTd.setColSpan(7);
			oTableTd.setAlign('center');
			oTableTd.setClass('NWCalendarTableDaysTd');
			var oSpan = document.createElement('span');
			oSpan.innerHTML = '&nbsp;';
			oTableTd.add(oSpan);
			oTableTr.add(oTableTd);
			oTable.add(oTableTr);
		}
		
		return oTable.output();
	}
}